﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Reflection;

namespace Universe.Computing.UCHostLib
{
    class FileReceiver
    {
        private const int BufferSize = 0x10000;
        public string ReceivedFileName
        {
            get;
            set;
        }
        public Socket ClientSocket
        {
            get;
            set;
        }
        public void ExecuteJob()
        {
            RecieveFile();
            FileInfo fi = new FileInfo(ReceivedFileName);
            string receivedFileNameFullName = fi.FullName;
            
            Assembly jobAssembly = Assembly.LoadFile(receivedFileNameFullName);
            Type[] typesInJobAssembly = jobAssembly.GetTypes();
            foreach (Type t in typesInJobAssembly)
            {
                Console.WriteLine(t);
            }
        }
        public void RecieveFile()
        {
            byte[] buffer = new byte[BufferSize];
            NetworkStream ns = new NetworkStream(ClientSocket);
            int tmpCount = ns.Read(buffer, 0, buffer.Length);
            Console.WriteLine("tmpCount==" + tmpCount);
            int fileSize = -1;
            if (tmpCount >= 4)
            {
                fileSize = BitConverter.ToInt32(buffer, 0);
            }
            Console.Write("File Size==" + fileSize);
            int contentReceived = tmpCount - 4;
            Guid guid = Guid.NewGuid();
            String assemblyName = guid.ToString();
            FileStream fs = new FileStream(assemblyName, FileMode.Create, FileAccess.Write);

            if (contentReceived > 0)
            {
                fs.Write(buffer, 4, contentReceived);
            }
            while (contentReceived < fileSize)
            {
                int readCount = ns.Read(buffer, 0, buffer.Length);
                contentReceived += readCount;
                fs.Write(buffer, 0, readCount);
            }
            fs.Close();
            ns.Close();
            ReceivedFileName = assemblyName;
        }
    }
}
